package fr.epri.user.action;

import com.opensymphony.xwork2.ActionSupport;
import fr.epri.user.Users;
import fr.epri.util.HibernateUtil;
import fr.epri.util.UserUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class WelcomeUserAction extends ActionSupport {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String execute() {
        UserUtil user = UserUtil.getInstance();
        if(user.getUser() != null) {
            username = user.getUser();
            return SUCCESS;
        }
        if(username == null) {
            return ERROR;
        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        String result;
        Criteria dbUser = session.createCriteria(Users.class);
        dbUser.add(Restrictions.eq("username", username));
        dbUser.add(Restrictions.eq("password", password));
        
        if (dbUser.list().isEmpty()) {
            result = ERROR;
            addActionError("Utilisateur/Mot de passe Invalide.");
            username=null;
        } else {
            result = SUCCESS;
            user.setUser(username);
        }
        
        session.close();

        return result;
    }
    
    public String begin() {
        return ERROR;
    }
}